from django.shortcuts import render
from django.core.paginator import Paginator
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from .serializers import *
import re
# Create your views here.


class AddCate(APIView):
    def post(self,request):
        name=request.data.get('name')
        cate=Cate.objects.filter(name=name).first()
        if cate:
            return Response({'msg':'分类已存在','code':1001})
        obj=CateSerializer(data=request.data)
        if obj.is_valid():
            flay=obj.save()
            if flay:
                return Response({'msg':'添加成功','code':1000})
            return Response({'msg': '添加失败', 'code': 1002})

    def get(self,request):
        cate=Cate.objects.all()
        obj=CateSerializer(cate,many=True)
        return Response(obj.data)


class AddGoods(APIView):
    def post(self,request):
        name = request.data.get('goods_name')
        price = request.data.get('price')
        grade = request.data.get('grade')
        if not re.match(r'\d{1,5}$',price):
            return Response({'msg': '价格错误', 'code': 400})
        if not re.match(r'([0-9]|10)$',grade):
            return Response({'msg': '评分错误', 'code': 400})
        goods = Goods.objects.filter(goods_name=name).first()
        if goods:
            return Response({'msg': '商品已存在', 'code': 1002})
        obj=GoodsSerializer(data=request.data)
        if obj.is_valid():
            flay=obj.save()
            if flay:
                return Response({'msg': '添加成功', 'code': 1000})
            return Response({'msg': '添加失败', 'code': 1001})


class Show(APIView):
    def get(self,request):
        uid=request.GET.get('uid')
        goods=Goods.objects.all()
        paginotor=Paginator(goods,3)
        paged=paginotor.page(uid)
        goods_serializer=GoodsSerializer(paged,many=True)
        return Response({'page_num':paginotor.num_pages,'page_list':[i for i in paginotor.page_range],'data':goods_serializer.data})


class AddReserve(APIView):
    def post(self,request):
        phone=request.data.get('phone')
        if not re.match(r'1[356789]\d{9}$',phone):
            return Response({'msg': '手机号错误', 'code': 1002})
        obj=ReserveSerializer(data=request.data)
        if obj.is_valid():
            obj.save()
            return Response({'msg': '添加成功', 'code': 1000})
        else:
            print(obj.errors)
            return Response({'msg': '添加失败', 'code': 1001})
